package com.bwsoft.portal.service.impl;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.bwsoft.admin.domain.Account;
import com.bwsoft.admin.domain.AccountAccess;
import com.bwsoft.admin.domain.Report;
import com.bwsoft.api.pojo.ResponsePojo;
import com.bwsoft.api.util.Constant;
import com.bwsoft.portal.domain.valueObject.ReportVO;
import com.bwsoft.portal.service.AccountAccessService;
import com.bwsoft.portal.service.ReportService;
import com.bwsoft.util.Base64Util;
import com.bwsoft.util.DesUtil;
import com.bwsoft.util.PDFUtil;
import com.bwsoft.util.UploadFileUtil;

@Service(ReportService.NAME)
public class ReportServiceImpl extends PortalBaseServiceImpl implements ReportService {
	private static Logger LOG = Logger.getLogger(ReportService.class.getClass());

	@Resource(name =  AccountAccessService.NAME)
	AccountAccessService accountAccessService;
	
	@Override
	public List<Report> findData(Integer page, Integer rows,
			String s_reportNumber, String s_sampleName, Account account) {
		
		StringBuffer reportHql = new StringBuffer();
		reportHql.append("from Report as rep where 1=1");
		if(s_reportNumber != null && !"".equals(s_reportNumber.trim())){
				reportHql.append(" and rep.reportNumber like '%"+s_reportNumber.trim()+"%'");
		}
		if(s_sampleName != null && !"".equals(s_sampleName.trim())){
			reportHql.append(" and rep.sampleName like '%"+s_sampleName.trim()+"%'");
		}
		Integer accountId = account.getAccountId();
		Integer accountType = account.getAccountType();
		if(accountId != null && accountType == 2){
			reportHql.append(" and rep.shangchuan.accountId="+accountId);
		} else if(accountId != null && accountType == 1){
			reportHql.append(" and rep.danwei.accountId="+accountId);
		}
		reportHql.append(" order by rep.addTime desc");
		List<Report> reportData = reportDao.findPage(reportHql.toString(), rows, (page - 1) * rows);
		
		return reportData;
	}

	@Override
	public Long getTotalCount(String s_reportNumber, String s_sampleName, Account account) {
		
		StringBuffer reportHql = new StringBuffer();
		reportHql.append("select count(*) from Report as rep where 1=1");
		if(s_reportNumber != null && !"".equals(s_reportNumber.trim())){
				reportHql.append(" and rep.reportNumber like '%"+s_reportNumber.trim()+"%'");
		}
		if(s_sampleName != null && !"".equals(s_sampleName.trim())){
			reportHql.append(" and rep.sampleName like '%"+s_sampleName.trim()+"%'");
		}
		Integer accountId = account.getAccountId();
		Integer accountType = account.getAccountType();
		if(accountId != null && accountType == 2){
			reportHql.append(" and rep.shangchuan.accountId="+accountId);
		} else if(accountId != null && accountType == 1){
			reportHql.append(" and rep.danwei.accountId="+accountId);
		}
		Long count;
		count = (Long)reportDao.findByHql(reportHql.toString()).get(0);
		return count;
	}

	@Override
	public List<ReportVO> getVo(List<Report> reports, Integer accountType) throws Exception {
		List<ReportVO> reportListVo = new ArrayList<ReportVO>();
		ReportVO reportVo = new ReportVO();
		for (Report report : reports) {
			reportVo = new ReportVO();
			reportVo.setAddTime(new SimpleDateFormat("yyyy-MM-dd").format(report.getAddTime()));
			if(report.getFile() != null && !"".equals(report.getFile())){
//				reportVo.setFilePath(report.getFile().getPath());
				reportVo.setFilePath("api/jsp/pdf.jsp?r="+Base64Util.getBase64(DesUtil.encrypt("fileid="+report.getFile().getId(), Constant.KEY_DES).getBytes("utf-8")));
			}
			reportVo.setReportId(report.getReportId());
			reportVo.setReportName(report.getReportName());
			reportVo.setReportNumber(report.getReportNumber());
			reportVo.setSampleName(report.getSampleName());
			reportVo.setScrqph(report.getScrqph());
			if(accountType == 1 && report.getShangchuan() != null && !"".equals(report.getShangchuan())){
				reportVo.setShangchuanCompName(report.getShangchuan().getCompName());
			} else if(accountType == 2 && report.getDanwei() != null && !"".equals(report.getDanwei())){
				reportVo.setShangchuanCompName(report.getDanwei().getCompName());
			}
			reportListVo.add(reportVo);
		}
		return reportListVo;
	}

	@Override
	public ResponsePojo checkCompName(String compName) {
		String hql = "";
		if (compName.matches("\\d+")) {
			hql = "from Account where accountType=1 and accountId=" + compName;
		} else {
			hql = "from Account where accountType=1 and compName='" + compName + "'";
		}
		List<Account> reportList = accountDao.findByHql(hql);
		ResponsePojo rp = new ResponsePojo();
		if (reportList.size() == 0) {
			rp.setErrcode(2);
			rp.setErrmsg("公司不存在！");
		} else {
			rp.setErrcode(0);
			rp.setErrmsg("获取成功！");
			rp.setData(reportList.get(0));
		}
		return rp;
	}

	@Override
	public ResponsePojo saveReport(Account company, Account account,
			String reportNumber, String sampleName, String scrqph, File report,
			String reportFileName) {
		Report newReport = new Report();
		ResponsePojo rp = new ResponsePojo();
		com.bwsoft.admin.domain.File filePojo = new com.bwsoft.admin.domain.File();
		try {
			newReport.setAddTime(new Date());
			//---------附件上传（如果没上传则取原数据库内容保存）--------------
			if(reportFileName != null && !"".equals(reportFileName)){
				Calendar now = Calendar.getInstance();
				String stdFilepath = ServletActionContext.getServletContext().getRealPath(Constant.PATH_PDF_QUALITYCONTROL+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1));
				String newFileName=null ;
				newFileName=UUID.randomUUID().toString()+reportFileName.substring(reportFileName.lastIndexOf('.'), reportFileName.length());
				UploadFileUtil.uploadOneFile(newFileName, report, stdFilepath);
				filePojo.setPath(Constant.PATH_PDF_QUALITYCONTROL+"/"+now.get(Calendar.YEAR)+(now.get(Calendar.MONTH) + 1)+"/"+newFileName);
				filePojo.setName(reportFileName);
				filePojo.setSize(String.valueOf(report.length()));
				filePojo.setAddTime(new Date());
				newReport.setFile(filePojo);
			}
			newReport.setSampleName(sampleName);
			newReport.setScrqph(scrqph);
			newReport.setReportNumber(reportNumber);
			newReport.setDanwei(company);
			newReport.setShangchuan(account);
			newReport.setReportName(reportFileName);
			reportDao.saveOrUpdate(newReport);
			rp.setErrcode(0);
			rp.setErrmsg("保存成功！");
		} catch (Exception e) {
			rp.setErrcode(10);
			rp.setErrmsg("保存失败");
			LOG.info(e);
		}
		return rp;
	}

	@Override
	public ResponsePojo saveMultiReport(Account company, Account uploader,
			File file, String fileFileName) {
		AccountAccess access = accountAccessService.find(uploader);
		ResponsePojo rp = new ResponsePojo();
		if (access == null) {
			rp.setErrcode(10);
			rp.setErrmsg("保存失败");
			return rp;
		}
		String[] strs=PDFUtil.readPDF(file);
		if (strs == null || strs.length == 0) {
			rp.setErrcode(10);
			rp.setErrmsg("保存失败");
			return rp;
		}
		return saveReport(company, uploader, strs[access.getReportNumber()], strs[access.getSampleName()], strs[access.getScrqph()], file, fileFileName);
	}

	
}
